package org.supda.system.service.impl;

import java.util.List;

import javax.transaction.Transactional;

import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.supda.system.dao.TMessageSendDao;
import org.supda.system.entity.TMessageSend;
import org.supda.system.entity.TUser;
import org.supda.system.service.TMessageSendService;
import org.supda.system.task.MessageMapSingleton;

@Service("TMessageSendService")
@Transactional
public class TMessageSendServiceImpl implements TMessageSendService{

	@Autowired private TMessageSendDao messageSendDao;
	
	@Override
	public void save(TMessageSend tMessageSend) {
		messageSendDao.save(tMessageSend);
	}

	@Override
	public List<TMessageSend> selectUnSendMessages(Long id) {
		
		//查询出所有未发送，并且未阅读的消息
		return messageSendDao.find(
				"FROM TMessageSend WHERE id.userId=? AND sendStatus IN (0,6) AND readFlag=0 ORDER BY sendTime", new Object[]{id});
	}

	@Override
	public List<TMessageSend> readMessages() {
		
		TUser user = (TUser)SecurityUtils.getSubject().getSession().getAttribute("userSession");
		
		List<TMessageSend> messagesends = null;
		
		if(user!=null){

			messagesends = MessageMapSingleton.getInstance().getMessages(user.getId());
			
			if(messagesends !=null ) {
				for(TMessageSend messageSend : messagesends){
					messageSend.setReadFlag(Short.parseShort("1"));
					messageSendDao.update(messageSend);
				}
			}
		}
		
		//清空未读消息缓存
		MessageMapSingleton.getInstance().setAttribute(user.getId(), null);
		
		return messagesends;
	}

	@Override
	public Integer getMsgCount(Long id) {
		
		List<TMessageSend> messageList = selectUnSendMessages(id);
		
		//缓存更新，初始化
		MessageMapSingleton.getInstance().setAttribute(id, messageList);
		
		return messageList!=null?messageList.size():0;
	}

	@Override
	public List<TMessageSend> readedMessages(Long id) {
		
		//查询出所有未发送，并且未阅读的消息
		return messageSendDao.find(
				"FROM TMessageSend WHERE id.userId=? AND readFlag=1 ORDER BY sendTime", new Object[]{id});
		
	}
}
